import Vue from 'vue'
import { createStore } from 'vuex'
import axios from 'axios'

export default createStore({
  state: {
    //所有的任务列表
    list: [],
    inputValue: 'aaa', //文本框内容
    nextId: 5, //下一个id
    viewKey: 'all',
  },
  getters: {
    // 统计未完成条数
    unDoneLength(state) {
      return state.list.filter((item) => {
        item.done === false
      }).length
    },
    infoLis(state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'undone') {
        return state.list.filter(() => {
          item.done === false
        })
      }
      if (state.viewKey === 'done') {
        return state.list.filter((item) => {
          item.done === true
        })
      }
    },
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    setInputValue(state, val) {
      state.inputValue = val
    },
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }

      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    removeItem(state, id) {
      const i = state.list.findIndex((item) => {
        item.id === id
      })
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    cbStatus(state, params) {
      const i = state.list.findIndex((item) => {
        item.id === params.id
      })
      if (i !== -1) {
        state.list[i].done = params.status
      }
    },
    cleanDone(state) {
      state.list = state.list.filter((item) => {
        item.done === false
      })
    },
    changeViewKey(state, key) {
      state.viewKey = key
    }
  },
  actions: {
    getList(context) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('initList', data)
      })
    },
  },
  modules: {
  }
})
